﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;

public class PersonalInfoEmailSettingActivity extends WuyangBaseActivity {
	private Button back_btn;
	private Button submit_btn;
	private String createAuthCode = "22";
	private EditText email_et;
	private EditText auth_code_et;
	private String email;
	private String true_email ;
	private String auth_code;
	private TextView please_auth_code_email;
	private TextView email_tv;
	public static int email_flag  = 0;
	private int flag = 0 ;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							com.alibaba.fastjson.JSONObject jsonObjectResult = JSON
									.parseObject(result);
							if (null != jsonObjectResult
									.getString("randomCode")) {
								String jsonStr = jsonObjectResult
										.getString("randomCode");
								createAuthCode = jsonStr;
								finishProgress();
								showToast("请求验证码成功");
							} 
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							showToast("请求验证码失败");
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("异常");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	
	private int time = MainConstants.TIMES;
	
	
	Handler time_handler = new Handler();
	Runnable run_time = new Runnable() {
		@Override
		public void run() {
			if(time > 0) {
				please_auth_code_email.setText(time + "秒后可再次发送");
				time--;
				time_handler.postDelayed(run_time, 1000);
			} else {
				time_handler.removeCallbacks(run_time);
				please_auth_code_email.setClickable(true);
				please_auth_code_email.setText("邮箱验证");
				time = MainConstants.TIMES;
			}
		}
	};
	
	
	protected JSONObject jsonObjectResult;
	Handler handler_UPDATE_EMAIL = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
								jsonObjectResult = JSON.parseObject(result);
								showToast("修改邮箱成功");
								Intent intent = new Intent();
								intent.putExtra("email", true_email);
								setResult(255, intent);
//								email_flag = 200;
								finishProgress();
								finish();
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							jsonObjectResult = JSON.parseObject(result);
							showToast(jsonObjectResult.getString("errorMsg"));
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("异常");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	private int userId;

	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.personal_info_email_setting);
		super.onCreate(savedInstanceState);
		this.setHeaderControlViewText();
		this.initBodyControlView();
		this.setBodyControlViewText();
		this.registerListener();
		userId = SharePrefenceUtil.getUserID(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.header_left:
			this.finish();
			break;
		case R.id.please_auth_code_email:// 发送短信验证码
			// showToast("模拟发送验证码");
			/*
			 * StringUtil stringUtil = new StringUtil(); createAuthCode =
			 * stringUtil.createAuthCode(); SendSmsUtil sendSmsUtil = new
			 * SendSmsUtil(this); sendSmsUtil.sendSms("15226160897",
			 * createAuthCode);
			 */
			flag = 200 ;
			this.getControlViewText();
			if (null == email || "".equals(email)||false == StringUtils.isEmail(email)) {
				showToast("请检查您输入的Email");
				break;
			}else{
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("mobileNumber", null));
				params.add(new BasicNameValuePair("userId", userId + ""));
				params.add(new BasicNameValuePair("email", email));
				new DataLoader(this).DisplayData(MainConstants.HOST_test
						+ HttpConfigAPI.RANDOM_CODE, params, handler, "", false);
				please_auth_code_email.setClickable(false);
				
				time_handler.postDelayed(run_time, 1000);
				
				/*new Handler().postDelayed(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						please_auth_code_email.setClickable(true);
						please_auth_code_email.setText("邮箱验证");
					}
				},MainConstants.TIME);*/
				showProgress("正在加载数据...");
			}
			break;
		case R.id.header_right:
			this.getControlViewText();
			if (null == email || "".equals(email)||false == StringUtils.isEmail(email)) {
				showToast("请检查您输入的Email");
				break;
			}
			if (null == auth_code || "".equals(auth_code)) {
				showToast("验证码未输入");
				break;
			}
			if (!auth_code.equals(createAuthCode)) {
				showToast("验证码错误！");
				break;
			}
			if(!true_email.equals(email)){
				showToast("两次输入的邮箱不一致！");
				break;
			}else{
				// 向服务器提交修改信息
				//showToast("向服务器提交修改信息" + email + "----" + auth_code);
				List<NameValuePair> params1 = new ArrayList<NameValuePair>();
				params1.add(new BasicNameValuePair("userId", userId + ""));
				params1.add(new BasicNameValuePair("email", true_email));
				params1.add(new BasicNameValuePair("randomCode",createAuthCode ));
				new DataLoader(this).DisplayData(MainConstants.HOST_test
						+ HttpConfigAPI.UPDATE_EMAIL, params1, handler_UPDATE_EMAIL, "", false);
				showProgress("正在加载数据...");
				break;
			}
		default:
			break;
		}
	}

	@Override
	protected void setHeaderControlViewText() {
		super.setHeaderTitleText(headerTitle, "电子邮箱");
		super.setHeaderLeftText(headerLeft, "返回");
		super.setHeaderRightText(headerRight, "提交");
	}

	@Override
	protected void initBodyControlView() {
		back_btn = (Button) this.findViewById(R.id.header_left);
		please_auth_code_email = (TextView) this
				.findViewById(R.id.please_auth_code_email);
		submit_btn = (Button) this.findViewById(R.id.header_right);
		email_et = (EditText) this.findViewById(R.id.include_1tv_1et_true_et);
		auth_code_et = (EditText) this.findViewById(R.id.auth_code);
		email_tv = (TextView) this.findViewById(R.id.include_1tv_1et_true_tv);
	}

	@Override
	protected void registerListener() {
		back_btn.setOnClickListener(this);
		please_auth_code_email.setOnClickListener(this);
		submit_btn.setOnClickListener(this);
	}

	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub
		email_tv.setText("邮  箱  号：");
	}

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub
		email = email_et.getText().toString();
		if(200 == flag ){
			true_email = email ;
			flag = 0 ;
		}
		auth_code = auth_code_et.getText().toString();
	}
}
